package textFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {
        Employee[] staff = new Employee[3];
        staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

        // Save all employee records to the file employee.dat
        try (PrintWriter out = new PrintWriter("employee.dat", "UTF-8")) {
            writeDate(out, staff);
        }

        // Retrieve all records into a new array
        try (Scanner in = new Scanner(
                new FileInputStream("employee.dat"), "UTF-8"
        )) {
            Employee[] newStaff = readData(in);

            for (Employee e : newStaff) {
                System.out.println(e);
            }
        }
    }

    /**
     * Write all employees in an array to a print writer.
     * @param out a print writer
     * @param employees an array of Employee
     * @throws IOException
     */
    private static void writeDate(PrintWriter out, Employee[] employees) throws IOException {
        // write number of employees
        out.println(employees.length);

        for (Employee e : employees) {
            writeEmployee(out, e);
        }
    }

    /**
     * Reads an array of employee from a scanner.
     * @param in a Scanner
     * @return an array of Employee objects
     */
    private static Employee[] readData(Scanner in) {
        // Retrieve the array length
        int n = in.nextInt();
        in.nextLine(); // consume a newline

        Employee[] employees = new Employee[n];
        for (int i = 0; i < n; i++) {
            employees[i] = readEmployee(in);
        }
        return employees;
    }

    /**
     * Write an employee data to a print writer.
     * @param out a print writer
     * @param e an Employee object
     */
    public static void writeEmployee(PrintWriter out, Employee e) {
        out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());
    }

    /**
     * Reads an employee data from a buffered reader.
     * @param in the Scanner
     * @return an Employee object
     */
    public static Employee readEmployee(Scanner in) {
        String line = in.nextLine();
        String[] tokens = line.split("\\|");
        String name = tokens[0];
        double salary = Double.parseDouble(tokens[1]);
        LocalDate hireDate = LocalDate.parse(tokens[2]);
        int year = hireDate.getYear();
        int month = hireDate.getMonthValue();
        int day = hireDate.getDayOfMonth();
        return new Employee(name, salary, year, month, day);
    }
}
